# -*- coding: utf-8 -*-
class GrantController < ApplicationController
  before_filter :employee_authorize
  before_filter :employee_action_hx
  before_filter :sys_before_log
  #before_filter :privilege_filter,:except=>[:grantsList,:newGrant,:auditGrant,:editGrant,:auditGrantForCancel,:grantsListForGrant,:grantsListForReceivable]

  def grantsList
  end
  
  def create
    begin
      grant = Grant.new
      grant.company_id = session[:company_id]
      grant.department_id = session[:department_id]
      grant.employee_id = session[:employee_id]
      grant.begin_date = params[:begin_date]
      grant.end_date = params[:end_date]
      grant.amount = params[:amount]
      grant.description = params[:description]
      grant.receivable_id = params[:receivable_id]
      grant.sales_strategy_id = params[:sales_strategy_id]
      grant.auditing_status = Constants::AUDIT_APPLY_ADD

      Sequence.transaction do
        #开始为销售订单取得流水号
        sequence = Sequence.find(:first,:conditions=>["company_id = ? AND sub_type = ?",session[:company_id],Grant.name])
        sequence.seq_no = sequence.seq_no + 1
        grant.seq_number = sequence.seq_no
        grant.order_number = sequence.ab + ":" + grant.seq_number.to_s + ":" + Date.today.to_s
        sequence.save!
        grant.save!
      end
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end
    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def update
    begin
      grant = Grant.find(params[:id])
      grant.begin_date = params[:begin_date]
      grant.end_date = params[:end_date]
      grant.description = params[:description]
      grant.sales_strategy_id = params[:sales_strategy_id]

      #如果是驳回新增，在编辑后，依然是申请新增
      if grant.auditing_status == Constants::REJECT_APPLY_ADD
        grant.auditing_status = Constants::AUDIT_APPLY_ADD
        grant.amount = params[:amount]
      else
        grant.auditing_status = Constants::AUDIT_APPLY_EDIT
        grant.new_amount = params[:amount]
      end
      grant.save!
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end
    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
  
  #得到某个销售订单的所有收款
  def getGrantsByReceivableId
    grants = Grant.find(:all,:conditions=>["receivable_id = ?" , params[:id]],:include=>[:employee,:sales_strategy])
    jsonStr = "{totalProperty:"+grants.length.to_s+",root:"+grants.to_json(:include=>[:employee,:sales_strategy])+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  def getGrantById
    grant = Grant.find(params[:id])
    rootStr = grant.to_json()
    jsonStr = "{root:["+rootStr+"]}"
    logger.info jsonStr
    render :json=>jsonStr, :layout=>false
  end

  #得到所有的预收款
  def getAllGrants
    begin
      conditionsHash = Hash.new
      paramsHash = Hash.new
      start = params[:start]
      limit = params[:limit]
      conditionsStr = ''

      if params[:customer_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'receivables.customer_id = :customer_id'
        else
          conditionsStr = conditionsStr+' AND receivables.customer_id = :customer_id'
        end
        conditionsHash[:customer_id] = params[:customer_id].to_i
      end
      
      if params[:begin_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'grants.begin_date >= :begin_date'
        else
          conditionsStr = conditionsStr+' AND grants.begin_date >= :begin_date'
        end
        conditionsHash[:begin_date] = params[:begin_date].to_date
      end

      if params[:end_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'grants.end_date >= :end_date'
        else
          conditionsStr = conditionsStr+' AND grants.end_date >= :end_date'
        end
        conditionsHash[:end_date] = params[:end_date].to_date
      end

      grants = Grant.find_all conditionsStr,conditionsHash
      grantsNow = grants.paginate start,limit

      jsonStr="{totalProperty:"+grants.length.to_s+",root:"+grantsNow.to_json(:include=>{:receivable=>{:include=>:customer},:sales_strategy=>{},:auditor=>{},:employee=>{}})+"}"
      logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  #审批，审批后，才计入销售订单的已收帐款
  def updateAuditingStatus
    grant = Grant.find(params[:id])
    info = nil
    if grant !=nil
      Grant.transaction do
        auditingStatus = params[:auditing_status]
        grant.auditor_id = session[:employee_id]
        grant.audit_opinion =  params[:audit_opinion]
        if(auditingStatus == "是")
          if grant.auditing_status == Constants::AUDIT_APPLY_EDIT
            auditingStatus = Constants::PASS_APPLY_EDIT
            grant.amount = grant.new_amount
            grant.new_amount = nil
          else
            auditingStatus = Constants::PASS_APPLY_ADD
          end
          grant.auditing_status = auditingStatus

        else
          if grant.auditing_status == Constants::AUDIT_APPLY_EDIT
            auditingStatus = Constants::REJECT_APPLY_EDIT
          else
            auditingStatus = Constants::REJECT_APPLY_ADD
          end
          grant.auditing_status = auditingStatus
        end
        grant.auditor_id = session[:employee_id]
        grant.save!
      end
      #结算表处理完毕。
      info = "成功"
    else
      info = "失败"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #根据审批的结果
  def updateAuditingCancelStatus
    grant = Grant.find(params[:id])
    Grant.transaction do
      if params[:auditing_status]=='是'
        grant.auditing_status = Constants::PASS_APPLY_CANCEL
        grant.audit_opinion = params[:audit_opinion]
      else
        grant.audit_opinion = params[:audit_opinion]
        grant.auditing_status = Constants::REJECT_APPLY_CANCEL
      end
      grant.auditor_id = session[:employee_id]
      grant.save!
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #申请撤消
  def applyToCancel
    grant = Grant.find(params[:id])
    #如果是通过新增则要审批，如果是申请状态则直接撤消
    if grant.auditing_status == Constants::PASS_APPLY_ADD  || grant.auditing_status == Constants::REJECT_APPLY_CANCEL
      grant.auditing_status = Constants::AUDIT_APPLY_CANCEL
    else
      grant.auditing_status = Constants::PASS_APPLY_CANCEL
    end
    grant.auditor_id = session[:employee_id]
    grant.save!

    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
  
end
